<template>
  <div class='container'>
    <el-card>
      <el-form :label-position="labelPosition" label-width="100px" :model="questionFromData" ref="question-form-data" :rules="rules">
        <el-form-item label="学科:" prop="subjectID">
          <el-select v-model="questionFromData.subjectID" @change="onChangeSubject" placeholder="请选择活动区域" style="width: 30%">
            <el-option v-for="(subject, i) in subjectList.data" :key="i" :label="subject.label" :value="subject.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" prop="catalogID">
          <el-select v-model="questionFromData.catalogID" placeholder="请选择活动区域" style="width: 30%">
            <el-option v-for="(simple, i) in simpleList.data" :key="i" :label="simple.label" :value="simple.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" prop='enterpriseID'>
          <el-select v-model="questionFromData.enterpriseID" placeholder="请选择活动区域" style="width: 30%">
            <el-option v-for="(company, i) in companyList.data.items" :key="i" :label="company.company" :value="company.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" label-width="100px" prop='province'>
          <el-select v-model="questionFromData.province" placeholder="请选择" @change="companyCity" style="width: 14.7%">
            <el-option v-for="(province, i) in provinces" :key="i" :label="province" :value="province" />
          </el-select>
          <el-select v-model="questionFromData.city" collapse-tags style="margin-left: 8px; width: 14.7%" placeholder="请选择">
            <el-option v-for="(city, i) in companyCitys" :key="i" :label="city" :value="city" />
          </el-select>
        </el-form-item>
        <el-form-item label="方向:" prop='direction'>
          <el-select v-model="questionFromData.direction" placeholder="请选择活动区域" style="width: 30%">
            <el-option v-for="(direction, i) in directions" :key="i" :label="direction" :value="direction" />
          </el-select>
        </el-form-item>
        <el-form-item label="题型:" prop='questionType'>
          <el-radio v-model="questionFromData.questionType" label="1">单选</el-radio>
          <el-radio v-model="questionFromData.questionType" label="2">多选</el-radio>
          <el-radio v-model="questionFromData.questionType" label="3">简答</el-radio>
        </el-form-item>
        <el-form-item label="难度:" prop='difficulty'>
          <el-radio v-model="questionFromData.difficulty" label="1">简单</el-radio>
          <el-radio v-model="questionFromData.difficulty" label="2">一般</el-radio>
          <el-radio v-model="questionFromData.difficulty" label="3">困难</el-radio>
        </el-form-item>
        <el-form-item label="题干:" prop='question'>
          <!-- 富文本编辑器, 容器 -->
          <vue-editor v-model="questionFromData.question" style="margin-bottom:50px;height:200px;"
                      :editorToolbar="questionEditorToolbar" useCustomImageHandler
                      @image-added="handleImageAdded">
          </vue-editor>
        </el-form-item>
        <el-form-item v-if="questionFromData.questionType != 3" label="选项:" prop='optionCode' >
          <div class="options" v-for="item in questionFromData.options" :key="item.code" >
            <div><el-radio v-if="questionFromData.questionType == 1" v-model="questionFromData.optionCode" :label="item.code">{{ item.code}}:</el-radio></div>
            <div><el-checkbox v-if="questionFromData.questionType == 2" v-model="questionFromData.optionCodes" :label="item.code">{{ item.code}}:</el-checkbox></div>
            <div><el-input v-model="item.title" style="margin-left:8px;width: 100%" /></div>
            <div>
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"

                >上传图片
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-circle-close avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </div>

        </el-form-item>
        <el-form-item label="" required>
          <el-button type="danger">+增加选项与答案</el-button>
        </el-form-item>
        <el-form-item label="解析视频:">
          <el-input v-model="input" placeholder="请输入内容" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="答案解析:" required>
          <!-- 富文本编辑器, 容器 -->
          <!--          <vue-editor v-model="questionFromData.answer" id="answer" style="height:400px;" :editorToolbar="answer" useCustomImageHandler @image-added="handleImageAdded"></vue-editor>-->
          <vue-editor v-model="questionFromData.answer" style="margin-bottom:50px; height:200px;"
                      :editorToolbar="questionEditorToolbar" useCustomImageHandler
                      @image-added="handleImageAdded">
          </vue-editor>
        </el-form-item>
        <el-form-item label="题目备注:" prop='remarks'>
          <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="questionFromData.remarks" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="试题标签:" required>
          <el-select v-model="questionFromData.tags" placeholder="请选择活动区域" style="width: 30%">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" required>
          <el-button type="primary" @click="onSubmit">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { provinces, citys } from '@/api/hmmm/citys'
import { direction } from '@/api/hmmm/constants'
import { questionAdd, questionModule } from '@/store/utils/addUtils'
import * as questionApi from '@/api/hmmm/questions'
import { VueEditor } from 'vue2-editor'
export default {
  data () {
    return {
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        province: [{ required: true, message: '请选择城市', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        optionCode: [{ required: true, message: '请选择正确答案', trigger: 'blur' }],
        // optionCodes: [{ required: true, message: '请选择正确答案', trigger: 'blur' }],
        remarks: [{ required: true, message: '请输入题目', trigger: 'blur' }]
      },
      questionEditorToolbar: [
        ['bold', 'italic', 'underline', 'color', 'strike'],
        [{
          list: 'ordered'
        }, {
          list: 'bullet'
        }],
        ['blockquote'],
        ['code', 'image', 'link']
      ],

      provinces: provinces(), //  省
      citys: [], // 城市
      directions: direction, // 方向
      companyCitys: [],
      imageUrl: '',
      dif: '1',
      check: '',
      input: '',
      labelPosition: 'right',
      questionFromData: {
        addData: '', // 录入时间
        catalog: '', // 目录
        city: '',
        creator: '', // 录入人
        difficulty: '1', // 难度
        subject: '', // 学科
        simple: '',
        number: '',// 试题编号
        question: '', // 题干
        questionType: '1', // 题型
        tags: '', // 标签
        direction: '', // 方向
        province: '',
        company: '',
        catalogID: '', // 目录ID
        answer: '',
        enterpriseID: '', // 企业ID
        subjectID: '',
        options: [
          {isRight: 0, code: "A", title: "", img: ""},
          {isRight: 0, code: "B", title: "", img: ""},
          {isRight: 0, code: "C", title: "", img: ""},
          {isRight: 0, code: "D", title: "", img: ""},
        ],
        optionCode: '',
        optionCodes: []
      }
    }
  },
  components: {
    VueEditor
  },

  computed: {
    ...mapState('companys', ['companyList']),
    ...mapState('questions', ['questionList','questionDatail', 'questionFormDatail']),
    ...mapState('subjects', ['subjectList', 'simpleList', 'tagList']),
  },
  methods: {
    ...mapActions('questions', ['updateQuestionList', 'updateQuestionDatail', 'updateQuestionFormDatail']),
    ...mapActions('subjects', ['updateSubjectList', 'updateSimpleList', 'updateTagList']),
    ...mapActions('companys', ['updateCompanyList']),
    // 富文本上传图片
    async handleImageAdded (file, Editor, cursorLocation, resetUploader) {
      // 一般情况下，我们都是提交json数据，但是现在要上传文件所以要使用FormData方式上传表单
      const formData = new FormData()
      // formData.append('file', file)
      formData.file = file
      // 发请求
      // let res = await upload(this.formData)
      // 把图片放在光标所在的位置

      let img = 'https://img2018.nblogs.com/blog/706116/201903/706116-20190319104230822-2016617567.png'
      console.log(formData.file)
      Editor.insertEmbed(cursorLocation, 'image', img)
      resetUploader()
    },
    onChangeSubject () {
      const data = this.questionFromData.subjectID
      this.updateSimpleList({
        subjectID: data
      })
      this.updateTagList({
        subjectID: data
      })
    },
    companyCity () {
      const data = citys(this.questionFromData.province)
      this.companyCitys = data
      this.companyFromData.city = this.companyCitys[0]
    },

    // 提交新增试题
    onSubmit () {
      this.$refs['question-form-data'].validate(async (valid) => {
        if (valid) {
          // 修改选项中的选中属性
          if (this.questionFromData.optionCode) { // 单选
            for (const item of this.questionFromData.options) {
              if (item.code === this.questionFromData.optionCode) {
                item.isRight = 1
              }
            }
          } else if (this.questionFromData.optionCodes) { // 多选
            for (const item of this.questionFromData.options) {
              if (this.questionFromData.optionCodes.some(tmp => tmp === item.code)) {
                item.isRight = 1
              }
            }
          }
          if (!this.$route.query.id) {
            await questionModule(questionApi.add, this.questionFromData, '新增')
          } else {
            await questionModule(questionApi.update, this.questionFromData, '修改')
          }
          // this.$router.go(-1)
          await this.$router.push('list')
        } else {
          console.log('error submit!!')
          this.$message.error('请填写必填项')
        }
      })
    },
    // 获取题目详情数据
    async getQuestionDatail() {
      // 跳转路由判断是新增还是修改
      if (this.$route.query.id) {
        await this.updateQuestionDatail({
          id: this.$route.query.id
        })
        // 定义空值来储存默认选中项
        this.questionDatail.optionCodes = []
        this.questionDatail.optionCode = ''
        // 遍历选项并赋值
        for (const item of this.questionDatail.options) {
          if (item.isRight === 1) {
            this.questionDatail.optionCode = item.code
            this.questionDatail.optionCodes.push(item.code)
          }
        }
        // 判断单选或多选，清除不需要的内容
        if (this.questionDatail.questionType == 1) {
          this.questionDatail.optionCodes = []
        } else if (this.questionDatail.questionType == 2) {
          this.questionDatail.optionCode = ''
        } else {
          this.questionDatail.optionCodes = []
          this.questionDatail.optionCode = ''
        }
        // 拷贝并赋值，解决默认选中以后无法选中其他选项的问题
        this.questionFromData = JSON.parse(JSON.stringify(this.questionDatail))
      }
    }
  },
  created () {
    this.getQuestionDatail()
    this.updateQuestionDatail()
    this.updateSubjectList()
    this.updateCompanyList()
  },
  // updated () {
  //   this.typeEditorHandle()
  //   this.answerEditorHandle()
  // }
}
</script>

<style scoped lang='scss'>
.container {
  margin: 16px;
}
.options {
  display: flex;
  align-items: center;
  margin-top: 8px;
}
.avatar-uploader {
  margin-left: 16px;
  text-align: center;
  line-height: 60px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 100px;
  height: 60px;
  position: relative;
  // overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  position: absolute;
  top: -5px;
  right: -5px;
  font-size: 14px;
  color: #ccc;
  text-align: center;
  background: #fff;
}
vue-editor{
  margin-bottom: 30px;
}
</style>
